const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const { UserBenefit, Visitor } = require("../models");

async function checkSubscriptionPaymentMethods() {
  try {
    console.log("开始检查订阅支付方式状态...");
    
    // 获取所有活跃的订阅用户
    const activeSubscriptions = await UserBenefit.findAll({
      where: {
        stripe_subscription_id: { [require('sequelize').Op.ne]: null },
        subscription_status: ['active', 'incomplete']
      },
      include: [{
        model: Visitor,
        as: 'visitor',
        attributes: ['uuid', 'email', 'membership_expires_at']
      }]
    });

    console.log(`找到 ${activeSubscriptions.length} 个活跃订阅`);
    
    let checkedCount = 0;
    let hasDefaultPaymentMethod = 0;
    let needsAttention = [];

    for (const userBenefit of activeSubscriptions) {
      try {
        // 获取Stripe订阅信息
        const subscription = await stripe.subscriptions.retrieve(userBenefit.stripe_subscription_id);
        
        // 获取客户信息
        const customer = await stripe.customers.retrieve(subscription.customer);
        
        const subscriptionInfo = {
          user_uuid: userBenefit.user_uuid,
          email: userBenefit.visitor?.email || 'Unknown',
          subscription_id: userBenefit.stripe_subscription_id,
          subscription_status: subscription.status,
          customer_id: subscription.customer,
          membership_expires_at: userBenefit.visitor?.membership_expires_at,
          default_payment_method: null,
          subscription_default_payment_method: null,
          has_payment_method: false
        };

        // 检查客户的默认支付方式
        if (customer.invoice_settings?.default_payment_method) {
          subscriptionInfo.default_payment_method = customer.invoice_settings.default_payment_method;
          subscriptionInfo.has_payment_method = true;
          hasDefaultPaymentMethod++;
        }

        // 检查订阅的默认支付方式
        if (subscription.default_payment_method) {
          subscriptionInfo.subscription_default_payment_method = subscription.default_payment_method;
          subscriptionInfo.has_payment_method = true;
        }

        // 如果没有任何默认支付方式，标记需要注意
        if (!subscriptionInfo.has_payment_method) {
          subscriptionInfo.issue = "没有默认支付方式 - 自动续费可能失败";
          needsAttention.push(subscriptionInfo);
        }

        console.log(`✓ 检查用户: ${subscriptionInfo.email}`);
        console.log(`  订阅ID: ${subscriptionInfo.subscription_id}`);
        console.log(`  订阅状态: ${subscriptionInfo.subscription_status}`);
        console.log(`  客户默认支付方式: ${subscriptionInfo.default_payment_method || '无'}`);
        console.log(`  订阅默认支付方式: ${subscriptionInfo.subscription_default_payment_method || '无'}`);
        console.log(`  会员到期时间: ${subscriptionInfo.membership_expires_at}`);
        
        if (subscriptionInfo.issue) {
          console.log(`  ⚠️  问题: ${subscriptionInfo.issue}`);
        }
        console.log('---');

        checkedCount++;
        
        // 避免频率限制
        await new Promise(resolve => setTimeout(resolve, 100));
        
      } catch (subscriptionError) {
        console.error(`检查订阅 ${userBenefit.stripe_subscription_id} 失败:`, subscriptionError.message);
        needsAttention.push({
          user_uuid: userBenefit.user_uuid,
          subscription_id: userBenefit.stripe_subscription_id,
          issue: `API错误: ${subscriptionError.message}`
        });
      }
    }

    // 输出总结
    console.log("\n" + "=".repeat(50));
    console.log("检查结果总结:");
    console.log(`总订阅数: ${activeSubscriptions.length}`);
    console.log(`成功检查: ${checkedCount}`);
    console.log(`有默认支付方式: ${hasDefaultPaymentMethod}`);
    console.log(`需要注意的订阅: ${needsAttention.length}`);

    if (needsAttention.length > 0) {
      console.log("\n⚠️  需要注意的订阅:");
      needsAttention.forEach((item, index) => {
        console.log(`${index + 1}. 用户: ${item.user_uuid}`);
        console.log(`   订阅: ${item.subscription_id}`);
        console.log(`   问题: ${item.issue}`);
      });
      
      console.log("\n💡 建议:");
      console.log("1. 联系这些用户更新支付方式");
      console.log("2. 或在下次支付失败时提示用户更新支付方式");
    } else {
      console.log("\n✅ 所有订阅都配置了默认支付方式，自动续费应该正常工作！");
    }

  } catch (error) {
    console.error("检查过程中发生错误:", error);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  checkSubscriptionPaymentMethods()
    .then(() => {
      console.log("\n检查完成");
      process.exit(0);
    })
    .catch((error) => {
      console.error("脚本执行失败:", error);
      process.exit(1);
    });
}

module.exports = { checkSubscriptionPaymentMethods }; 